<template>
    <div claas="component-container">
        <!-- 搜索表单 -->
        <el-form
                ref="queryFormRef"
                size="mini"
                :model="queryParams"
                :inline="true"
        >
            <el-form-item>
                <el-button type="success" :icon="Plus" :disabled="!menuId" @click="handleAdd">新增</el-button>
                <el-button type="danger" :icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
            </el-form-item>
            <el-form-item prop="name">
                <el-input
                        v-model="queryParams.name"
                        placeholder="按钮名称"
                        clearable
                        @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
                <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 数据表格 -->
        <el-table
                :data="pageList"
                v-loading="loading"
                @selection-change="handleSelectionChange"
                border
                size="mini"
        >
            <el-table-column type="selection" width="40" align="center"/>
            <el-table-column label="按钮名称" prop="name" width="150"/>
            <el-table-column label="按钮标识" prop="identifier" width="150"/>
            <el-table-column label="所属服务" prop="functionalModule" width="150"/>
            <el-table-column label="序号" prop="sort" width="50"/>
            <el-table-column label="操作" align="center" width="100">
                <template #default="scope">
                    <el-button
                            type="primary"
                            :icon="Edit"
                            size="mini"
                            circle
                            plain
                            @click="handleUpdate(scope.row)"
                    />
                    <el-button
                            type="danger"
                            :icon="Delete"
                            size="mini"
                            circle
                            plain
                            @click="handleDelete(scope.row)"
                    />
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页工具条 -->
        <pagination
                v-show="total>0"
                :total="total"
                :page="queryParams.pageNum"
                :limit="queryParams.pageSize"
                @pagination="handleQuery"
        />

        <!-- 表单弹窗 -->
        <el-dialog
                :title="dialog.title"
                v-model="dialog.visible"
                width="700px">
            <el-form
                    ref="dataFormRef"
                    :model="formData"
                    :rules="rules"
                    label-width="120px"
            >

                <el-form-item label="按钮名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入按钮名称"/>
                </el-form-item>

                <el-form-item label="按钮序号" >
                    <el-input type="number" v-model="formData.sort" placeholder="请输入按钮序号"/>
                </el-form-item>

                <el-form-item label="功能模块" prop="functionalModule">
                    <el-select v-model="formData.functionalModule" class="m-2" placeholder="user">
                        <el-option
                                v-for="item in functionalModuleOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="按钮权限标识" prop="identifier">
                    <el-input v-model="formData.identifier" placeholder="时间戳：1651742775"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
    import {listPermsWithPage, getPermDetail, addPerm, updatePerm, deletePerms} from "@/api/system/perm"
    import {Search, Plus, Edit, Refresh, Delete} from '@element-plus/icons'
    import {onMounted, watch, reactive, ref, unref, getCurrentInstance, toRefs} from 'vue'
    import {ElForm, ElMessage, ElMessageBox} from "element-plus"

    const {proxy}: any = getCurrentInstance();

    const queryFormRef = ref(ElForm)
    const dataFormRef = ref(ElForm)

    const functionalModuleOption = [
        {
            value: 'user',
            label: 'user',
        },
        {
            value: 'order',
            label: 'order',
        },
        {
            value: 'produce',
            label: 'produce',
        },
        {
            value: 'procurement',
            label: 'procurement',
        },
        {
            value: 'warehouse',
            label: 'warehouse',
        },
    ]

    const props = defineProps({
        menuId: {
            type: String,
            default: ''
        }
    })

    watch(() => props.menuId as any, (newVal, oldVal) => {
        console.log("监听到菜单id在变化：" + newVal);
        state.queryParams.menuId = newVal
        handleQuery()
    })

    const state = reactive({
        loading: true,
        // 选中ID数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        queryParams: {
            pageNum: 1,
            pageSize: 10,
            menuId: undefined,
            name: undefined
        },
        pageList: [],
        total: 0,
        dialog: {
            title: '',
            visible: false
        },
        formData: {
            id: undefined,
            name: undefined,
            identifier: undefined,
            functionalModule: undefined,
            sort: undefined,
            menuId: ''
        },
        rules: {
            name: [
                {required: true, message: '请输入权限名称', trigger: 'blur'}
            ],
            perm: [
                {required: true, message: '请输入权限标识', trigger: 'blur'}
            ],
            method: [
                {required: true, message: '请选择请求方式', trigger: 'blur'}
            ]
        },
        microServiceOptions: [] as Array<any>,
        requestMethodOptions: [] as Array<any>,
        urlPerm: {
            requestMethod: undefined,
            serviceName: undefined,
            requestPath: undefined
        },
    })

    const {
        loading,
        ids,
        single,
        multiple,
        pageList,
        total,
        dialog,
        formData,
        rules,
        microServiceOptions,
        requestMethodOptions,
        urlPerm,
        queryParams
    } = toRefs(state)

    function handleQuery() {
        console.log("btn-2")
        if (state.queryParams.menuId) {
            console.log("btn-3")
            state.loading = true
            listPermsWithPage(state.queryParams).then(response => {
                const {data} = response as any
                console.log("按钮list：" + data)
                state.pageList = data
                state.total = 0
                state.loading = false
            })
        } else {
            console.log("btn-4")
            state.loading = false
            state.pageList = []
            state.total = 0
            state.queryParams.pageNum = 1
        }
    }

    function resetQuery() {
        const queryForm = unref(queryFormRef)
        queryForm.resetFields()
        handleQuery()
    }

    function handleSelectionChange(selection: any) {
        state.ids = selection.map((item: any) => item.id)
        state.single = selection.length !== 1
        state.multiple = !selection.length
    }

    /**
     * 加载字典数据
     */
    function loadDictOptions() {
        proxy.$listDictsByCode('micro_service').then((response: any) => {
            state.microServiceOptions = response.data
        })

        proxy.$listDictsByCode('request_method').then((response: any) => {
            state.requestMethodOptions = response.data
        })
    }

    function handleAdd() {
        state.formData.id = undefined;
        state.dialog = {
            title: '添加权限',
            visible: true
        }
    }

    function handleUpdate(row: any) {
        state.dialog = {
            title: '修改权限',
            visible: true
        }
        const id = row.id || state.ids
        getPermDetail(id).then(response => {
            const {data} = response
            state.formData = data
        })
    }

    function submitForm() {
        const dataForm = unref(dataFormRef)
        dataForm.validate((valid: any) => {
            if (valid) {
                state.formData.menuId = props.menuId
                if (state.formData.id) {
                    updatePerm(state.formData).then(response => {
                        ElMessage.success('修改成功')
                        state.dialog.visible = false
                        resetForm()
                        handleQuery()
                    })
                } else {
                    addPerm(state.formData).then(response => {
                        ElMessage.success('新增成功')
                        state.dialog.visible = false
                        resetForm()
                        handleQuery()
                    })
                }
            }
        })
    }

    /**
     * 重置表单
     */
    function resetForm() {
        const dataForm = unref(dataFormRef)
        dataForm.resetFields()

    }

    function cancel() {
        resetForm()
        state.dialog.visible = false
    }

    function handleDelete(row: any) {
        const ids = [row.id || state.ids].join(',')
        ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            deletePerms(ids).then(() => {
                ElMessage.success('删除成功')
                handleQuery()
            })
        }).catch(() =>
            ElMessage.info('已取消删除')
        )
    }

    onMounted(() => {
        console.log("btn-1")
        handleQuery()
    })
</script>

<style scoped>
    .component-container {
        margin-bottom: 20px;
    }
</style>

